/*
 * @Author: your name
 * @Date: 2021-10-11 10:58:38
 * @LastEditTime: 2022-01-18 11:27:44
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \drug-admin\src\service\axios.js
 */
import axios from 'axios'
import Vue from 'vue'
// 全局默认配置
// 设置 POST 请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 60000
// axios.defaults.baseURL = '/' // api 即vue.config.js 中配置的地址

// 配置 CORS 跨域
// axios.defaults.withCredentials = true
// axios.defaults.crossDomain = true

// 请求发起前拦截器
axios.interceptors.request.use(config => {
  const token = window.sessionStorage.getItem('platformToken')
  // const token = '6b1ba138-2d61-11ec-a12e-0242ac110006'
  if (token) config.headers.token = token
  return config
}, error => {
  // 异常处理
  return Promise.reject(error)
})
// 响应拦截
axios.interceptors.response.use(response => {
  const { code, msg } = response.data
  if (code === 407 || code === 405) {
    Vue.prototype.$message.error(msg)
  }
  return response.data
}, error => {
  if (error.response) {
    const statusCode = parseFloat(error.response.status)
    const statusMsg = error.response.data.message
    switch (statusCode) {
      case 401:
        Vue.prototype.$alert('用戶登录已过期或被其它设备登录, 请重新登录', '提示', {
          confirmButtonText: '确定',
          showClose: false,
          type: 'warning'
        }).then(() => {
          window.location.href = 'https://www.ynyplt.com'
        }).catch(() => {
        })

        break
      default:
        Vue.prototype.$message.error(`【${statusCode}】 - ${statusMsg}`)
        break
    }
  } else {
    Vue.prototype.$message.error(`【${error}】 - 网络超时`)
  }

  return Promise.reject(error)
})

// 导出
export default axios
